const logger = require("koa-logger");
const serve = require("koa-static");
const koaBody = require("koa-body");
const Koa = require('koa');
const fs = require("fs");
const app = new Koa();
const os = require("os");
const path = require("path");
const mysql = require('mysql2/promise');

let con = mysql.createPool({
  host:'154.8.156.240',
  port:'2020',
  user:'root',
  password:'Ljj0222.',
  database:'tuijian'
});

//const today = require('./time');
//const date = require("silly-datetime");
//var today = date.format(new Date(),'YYYY-MM-DD');

Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "S": this.getMilliseconds() //毫秒 
        };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



app.use(logger());

app.use(koaBody({ multipart: true }));

app.use(serve(path.join(__dirname, '/public')));
app.use(async function (ctx, next) {
	    await next();
	    if (ctx.body || !ctx.idempotent) return;
	    ctx.body = {
              title: '404 not pic'
	    }
})

//查询id
async function insertSJ1(){
  const sql1 = `select max(share_id) id from main_table`;
  let rows = await con.execute(sql1);
  return rows;
}
let id1;
(async function(){
  //let id1 = await insertSJ1(); 
  id1 = ((await insertSJ1())[0])[0].id + 1;
})();

var userid,title1,text1,food1,tags1,addr1,today,top1,size1,jwd1;

var str = [];
var temp;
app.use(async function (ctx, next) {
	    
    if ('POST' != ctx.method) return await next();
    //获取图片源
    
    const file = ctx.request.files.img;
    const type = (file.type).split('/')[1];
    const reader = fs.createReadStream(file.path);
    //console.log(ctx.request.body);
    //接收读出流
    //创建写入流
    //指定图片路径文件名
    //要重新写
    let data = ctx.request.body;
  
    var dirname = data.openid;

    userid = dirname;
    title1 = data.title;
    console.log(title1);
    text1 = data.text;
    food1 = data.food;
    tags1 = data.tags;
    addr1 = data.addr;
    today = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    top1 = data.top;
    size1 = data.size;
    jwd1 = data.jwd;
    //数据库插入携带过来的form-data
    
    var filename = 'img'+`${i}`+'.'+`${type}`;
    console.log(filename);
    str[i] = filename;
    temp = i;
    
    
    setTimeout(function(){ i = 1;console.log(i) },5000);
    //加一个插入数据库文件名
     try {
      if(fs.existsSync("public/images/"+dirname)){
        console.log('文件夹存在');
        if(!fs.existsSync('public/images/'+dirname+'/'+`${id1}`)){
          fs.mkdirSync('public/images/'+dirname+'/'+`${id1}`,app.callback());
        }
        
        const stream = fs.createWriteStream(path.join(`public/images/${dirname}/${id1}`, filename));
        reader.pipe(stream);
      }else{
        console.log('文件夹不存在');
        fs.mkdirSync("public/images/"+dirname,app.callback());
        fs.mkdirSync('public/images/'+dirname+'/'+`${id1}`,app.callback());
        const stream = fs.createWriteStream(path.join(`public/images/${dirname}/${id1}`, filename));
	      reader.pipe(stream);
      }
    }catch(e){
      console.log(e);
    }
    i++;
    ctx.body = '上传成功';
    await next();
})

var i = 1;
var arr = [];
app.use(async function (ctx,next) {
  //插入main_table的数据
  async function insertDB(){
    const sql = `INSERT INTO main_table (user_id,shop_id,title,text,addr,date,food,tags,top,judge,jwd)VALUES ('${userid}','2','${title1}','${text1}','${addr1}','${today}','${food1}','${tags1}','${top1}',0,'${jwd1}')`;
    let [rows] = await con.execute(sql);
    return rows;
  }
  
  //很偷懒的写法，5秒后将arr值赋为空，才可再次上传
  if(arr.length == 0){
    //执行插入main_table函数
    arr[0] = insertDB();
    //插入img_table数据
    async function insertSJ(){
      const sql1 = `INSERT INTO img_table (id) VALUES ('${id1}')`;
      let rows = await con.execute(sql1);
      return rows;
    }
    async function upSZ(){
      const sq2 = `UPDATE img_table SET size = '${size1}' WHERE (id = '${id1}')`;
      let rows = await con.execute(sq2);
      return rows;
    }
    setTimeout(function(){
      //先插入id数据
      (async function(){
        await insertSJ();
      })();
      //插入size
      (async function(){
        await upSZ();
      })();
      //循环插入图片的img数据
      for(var m = 1; m <= temp; m++){
        async function update(){
          const sql1 = `UPDATE img_table SET img${m} = '/public/images/${userid}/${id1}/${str[m]}' WHERE (id = '${id1}')`;
          let rows = await con.execute(sql1);
          return rows;
        }
        (async function(){
          await update();
        })();
      }
      
      //console.log(temp);
      
      
      id1++;
      console.log(str); 
    },5000);

  }
  setTimeout(function(){ arr = []; },5000);
  
})

//(async function insertDB(){
//  console.log(await insertDB());
//});
//


app.listen(3002, () => {
})
